package com.dxy.hms.auth;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.dxy.hms.base.AppConstant;
import com.dxy.hms.base.StatusMessageEnum;
import com.dxy.hms.base.UnifiedException;
import com.dxy.hms.model.entity.User;
import com.dxy.hms.manager.UserCacheManager;
import com.dxy.hms.utils.JwtUtil;
import com.dxy.hms.utils.LoginUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Slf4j
@Data
@Configuration
@ConfigurationProperties(prefix = "auth")
public class AuthInterceptor implements WebMvcConfigurer {

    private List<String> excludePathPatterns;

    @Bean
    public HandlerInterceptor hmsAuthInterceptor() {
        return new HandlerInterceptor() {

            // 此处可以优化为缓存
            @Autowired
            private UserCacheManager userCacheManager;

            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                String token = LoginUtil.getToken(request);
                if (StrUtil.isEmpty(token) || !LoginUtil.checkLogin(token)) {
                    String servletPath = request.getServletPath();
                    log.debug("AuthInterceptor path: {}", servletPath);
                    throw new UnifiedException(StatusMessageEnum.UN_LOGIN);
                }

                String userId = JwtUtil.getUserId(token);
                User user = userCacheManager.getById(Long.parseLong(userId));

                if (user == null) {
                    throw new UnifiedException(StatusMessageEnum.ACCOUNT_NOT_EXIST);
                }

                if (!user.getStatus().equals(AppConstant.USER_ENABLE_STATUS)) {
                    throw new UnifiedException(StatusMessageEnum.ACCOUNT_DISABLE);
                }

                LoginUser loginUser = new DefaultLoginUser(user);
                UserContextHolder.set(loginUser);
                return true;
            }


            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
                UserContextHolder.remove();
            }
        };
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration interceptorRegistration = registry.addInterceptor(hmsAuthInterceptor());
        if (CollUtil.isNotEmpty(excludePathPatterns)){
            interceptorRegistration.excludePathPatterns(excludePathPatterns);
            System.out.println("Excluded paths: " + excludePathPatterns);
        }
        interceptorRegistration.addPathPatterns("/**"); // 确保拦截器注册了路径
    }
}
